package org.yczbj.ycvideoplayer.fraction;

import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.ListContainer;
import ohos.agp.utils.Rect;

import org.yczbj.ycvideoplayer.adapter.VideoRecyclerViewAdapter;

/**
 * 滑动列表自动播放，仅包含自动播放的逻辑
 *
 * @since 2021-05-12
 */
public class RecyclerViewAutoPlayFragment extends RecyclerViewFragment {
    /**
     * 构造函数
     */
    public RecyclerViewAutoPlayFragment() {
    }

    @Override
    protected void initComponent(Component component, Intent intent) {
        super.initComponent(component, intent);
        mListContainer.addScrolledListener(new Component.ScrolledListener() {
            @Override
            public void onContentScrolled(Component component, int i, int i1, int i2, int i3) {
            }

            @Override
            public void scrolledStageUpdate(Component component, int newStage) {
                if (newStage == Component.SCROLL_IDLE_STAGE) {
                    // 滚动停止
                    autoPlayVideo(component);
                }
            }

            private void autoPlayVideo(Component component1) {
                ListContainer view = (ListContainer) component1;
                if (view == null) {
                    return;
                }

                // 遍历RecyclerView子控件,如果mPlayerContainer完全可见就开始播放
                int count = view.getChildCount();
                for (int i = 0; i < count; i++) {
                    Component itemView = view.getComponentAt(i);
                    if (itemView == null) {
                        continue;
                    }
                    VideoRecyclerViewAdapter.Holder holder = (VideoRecyclerViewAdapter.Holder) itemView.getTag();
                    Rect rect = new Rect();
                    holder.mPlayerContainer.getSelfVisibleRect(rect);

                    // 获取item的高度
                    int height = holder.mPlayerContainer.getHeight();
                    if (rect.top == 0 && rect.bottom == height) {
                        startPlay(holder.mPosition);
                        break;
                    }
                }
            }
        });
    }

    @Override
    protected void initData() {
        super.initData();
        post(new Runnable() {
            @Override
            public void run() {
                // 自动播放第一个
                startPlay(0);
            }
        }, 50);
    }
}
